import json

from celery.result import AsyncResult
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.


from mycelery.celery_app import celery_app
from mycelery.email.tasks import send_email


# 首页
def index(request, *args, **kwargs):
    if request.method == "GET":
        return render(request, 'index.html')


# 创建任务
def create_task(request, *args, **kwargs):
    who = request.POST.get("who") or "默认管理员"
    # 执行异步任务
    task_id = send_email.delay(who)
    return JsonResponse({
        "code": 0,
        "msg": "success",
        "data": {
            "task_id": task_id.id
        }
    })


# 处理异步任务结果
def analysis_results(celery_task_result: AsyncResult):
    if celery_task_result.successful():
        data = json.loads(celery_task_result.get())
        return data
    if celery_task_result.failed():
        return {"code": 2311, "msg": "failed"}
    if celery_task_result.status == "PENDING":
        return {"code": 4252, "msg": "等待中"}
    if celery_task_result.status == "RETRY":
        return {"code": 5431, "msg": "正在重试"}
    if celery_task_result.status == "STARTED":
        return {"code": 4536, "msg": "进行中"}
    return {"code": 3234, "msg": "错误"}


# 获取任务状态
def get_task_status(request, *args, **kwargs):
    task_id = request.POST.get("task_id")
    result = AsyncResult(id=task_id, app=celery_app)
    res = {"code": 0, "msg": "", "data": {}}
    res.update(analysis_results(result))
    return JsonResponse(res)
